import json
import os

def apply_patches(repositories_file, patches_file):
    # Load repositories JSON file
    with open(repositories_file, 'r') as file:
        repositories_data = json.load(file)

    # Load patches JSON file
    with open(patches_file, 'r') as file:
        patches_data = json.load(file)

    # Get the path of the first incubator repository
    incubator_repo_path = None
    if "incubator_projects" in repositories_data:
        incubator_projects = repositories_data["incubator_projects"]
        if len(incubator_projects) > 0:
            incubator_repo_path = incubator_projects[0]['path']

    if incubator_repo_path is None:
        print("No incubator repository found in repositories.json")
        return

    # Iterate over patches and apply them to the corresponding projects
    for patch_info in patches_data['patches']:
        project_name = patch_info['project']
        patch_file = patch_info['patch_file']

        # Find the project path in repositories data
        project_path = None
        for project in repositories_data['mainline_projects']:
            if project['name'] == project_name:
                project_path = project['path']
                break

        if project_path is not None:
            # Construct the path to the patches directory in the first incubator repository
            patches_dir = os.path.join(project_path, incubator_repo_path, 'patches')

            # Apply the patch
            patch_path = os.path.join(patches_dir, patch_file)
            project_dir = os.path.join(project_path, 'mainline_project')
            apply_patch(patch_path, project_dir)
        else
            print(f"Project path not found for project: {project_name}")

def apply_patch(patch_path, project_dir):
    # Apply the patch using the 'patch' command or any other suitable method
    # This implementation assumes the 'patch' command is available
    command = f"patch -p1 -d {project_dir} < {patch_path}"
    os.system(command)

if __name__ == "__main__":
    repositories_file = 'repositories.json'
    patches_file = 'patches.json'

    # Apply patches to the mainline repositories
    apply_patches(repositories_file, patches_file)
